var interval = 0;

$(function() {
	get_users(gid);
	$('#login-btn').click(login());
	$('#start-btn').click(start_game());
	
	if ($('#game-mems').val().length == 0)
		$('#start-btn').toggle(false);
	
	interval = setInterval("refresh()", 5000);
});

// gets boolean true or false called 'success'
function login() {
	$.getJSON('', {
			userName: $('#userName').val(),
		}, function(data) {
			if (data.success == true) {
				$('#userName').val("");
				refresh();
			} else {
				alert("Unable to log in.");
			}
		});
}

// gets an array of strings for all 'logged in'/'connected' users.  array is called 'users'
// needs gid
function get_users() {
	$.getJSON('', {
			gid: $('#gid').val()
		}, function(data) {
			$('#game-mems').val("");
			for(var i in data.users) {
				$('#game-mems').val($('#game-mems').val()+data.users[i]+"\n");
			}
			
			if ($('#game-mems').val().length > 0)
				$('#start-btn').toggle(true);
		});
}

// gets boolean 'success', and int 'gid' (if success is true).  Matt's code sets eid to -1.
function start_game() {
	$.getJSON('', {
			gid: $('#gid').val()
		}, function(data) {
			if (data.success == true)
				refresh();
			else
				alert("Could not start game.");
		});
}

// gets integer that's the difference between our eid and the current game's eid.  'eid_dif'
// needs gid and eid
function refresh() {
	$.getJSON('', {
			gid: $('#gid').val(),
			eid: $('#eid').val()
		}, function(data) {
			if (data.eid_dif > 0) {
				$('#eid').val(+$('#eid').val() + +data.eid_dif);
				get_users();
			} else if (data.eid_dif < 0) {
				window.location = window.location + "/board.html";
			}
		});
}

// do later?
// needs userName
function create_group() {}